import mode from "../../data/mode.js";
import time from "../tool/time.js";
import localforage from "localforage";




function urlToBase64(url) {
	return new Promise((resolve) => {
		fetch(url).then(data => {
			const blob = data.blob()
			return blob;
		}).then(blob => {
			let reader = new FileReader()
			reader.onloadend = function() {
				const dataURL = reader.result
				resolve(dataURL)
			}
			reader.readAsDataURL(blob)
		})

	})
}

function getBase64ImageSize(base64) {
    let str = atob(base64.split(',')[1]);
    let bytes = str.length;
	
    return bytes;
}


async function  setCache(file, message) {
	try {
		let name = file?.name || "未定义"
			
		//列表
		if(file?.list == true){
		
	       let listName = file?.listName || "未定义"
		   let oldData = await localforage.getItem(listName) || {}
		   oldData[name] = true
		
			 localforage.setItem(name,file)
			 localforage.setItem(listName,oldData)
			 
			 return
			
		}
		 localforage.setItem(name,file)
	} catch (error) {
		console.log(error)
	}
}


async function saveFileByH5(path, cacheData) {


	const reader = new FileReader();
	let imageBase64 = await urlToBase64(path)
	
	let image = {
		...mode.getCacheMode(),
		...cacheData
	}
	image.data = imageBase64
    image.size = getBase64ImageSize(imageBase64)
	
	setCache(image, "文件太大无法缓存")
	return image

}

async function saveFileByUniApp(path, cacheData) {
	return new Promise((resolve, reject) => {
		uni.saveFile({
			tempFilePath:path, //临时路径
			success: (res) => {
				let data = {}
				data.data = res.savedFilePath
				data.size = 0
				resolve(data)
				let image = {
					...mode.getCacheMode(),
					...cacheData
				}
				image.data = res.savedFilePath
				setCache(image, "文件太大无法缓存")
			},
			fail: (err) => {
				reject(err)
			}

		})
	})
}



function isH5() {
	let message = 'ƒ (n){e.error("API `"+t+"` is not yet implemented")}'
	return uni.saveFile == message 
}





export default {

	//缓存临时路径
	downloadFile(url) {
		return new Promise((resolve, reject) => {
			try{

				uni.downloadFile({
					url,
					timeout: 60000,
					
					success: (data) => {
						if (data.statusCode === 200) {
							resolve(data)
						} else reject(data.errMsg)
					},
					fail: (err) => {
						console.log(err)
						reject(err)
					},
				})
			}catch(e){
				console.log(e)
			}
		})
	},

	//保存文件到本地
	saveFile(path, cacheData) {
		return new Promise(async (resolve, reject) => {
            let res = await saveFileByH5(path, cacheData) 
			resolve(res)

		})
	}


}